/*
    SerialSemi.h - Serial port over Semihosting for ARM
    Copyright (c) 2024 Earle F. Philhower, III.  All rights reserved.

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#pragma once

#include "Semihosting.h"

#include "Arduino.h"
#include "api/HardwareSerial.h"

class SerialSemiClass : public arduino::HardwareSerial {
public:
    SerialSemiClass() {
        /* noop */
    }

    ~SerialSemiClass() {
        /* noop */
    }

    void begin(unsigned long baudIgnored = 115200) override {
        (void)baudIgnored;
    }

    void begin(unsigned long baudIgnored, uint16_t configIgnored) override {
        (void)baudIgnored;
        (void)configIgnored;
    }

    void end() override {
        /* noop */
    }

    virtual int peek() override {
        // Can't really peek on SH, so fake it best we can
        if (!_peeked) {
            _peekedChar = read();
            _peeked = true;
        }
        return _peekedChar;
    }

    virtual int read() override {
        if (_peeked) {
            _peeked = false;
            return _peekedChar;
        }
        return Semihost(SEMIHOST_SYS_READC, nullptr);
    }

    virtual int available() override {
        // Can't really tell with SH, so always true.  Buyer beware
        return 1;
    }

    virtual int availableForWrite() override {
        // Can't really tell with SH, so always true.  Buyer beware
        return 1;
    }

    virtual void flush() override {
        /* noop */
    }

    virtual size_t write(uint8_t c) override {
        int32_t param = c;
        Semihost(SEMIHOST_SYS_WRITEC, &param);
        return 1;
    }

    using Print::write;

    operator bool() override {
        return true;
    }

private:
    bool _peeked = false;
    uint8_t _peekedChar;
};

extern SerialSemiClass SerialSemi;
